package com.echo.neocommunity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.echo.neocommunity.annotation.LoginRequired;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.impl.UserServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import com.echo.neocommunity.utils.CommunityUtil;
import com.echo.neocommunity.utils.R;
import com.echo.neocommunity.utils.RedisKeyUtils;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private Producer producer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    private static final Logger logger= LoggerFactory.getLogger(LoginController.class);

    @GetMapping("/register")
    public String getRegisterPage(){
        return "/site/register";
    }

    @PostMapping("/register")
    public String register(Model model, User user){
        Map<String, Object> register = userService.register(user);
        if(register==null||register.isEmpty()){
            model.addAttribute("msg","注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活！");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("usernameMsg",register.get("usernameMsg"));
            model.addAttribute("passwordMsg",register.get("passwordMsg"));
            model.addAttribute("emailMsg",register.get("emailMsg"));
            return "/site/register";
        }
    }

    @GetMapping("/activation/{id}/{code}")
    public String activation(Model model, @PathVariable("id") int id, @PathVariable("code") String code){
        int result = userService.activation(id, code);
        if(result== CommunityConstant.ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功，您的账号已经可以正常使用了！");
            model.addAttribute("target","/login");
        }else if(result==CommunityConstant.ACTIVATION_REPEAT){
            model.addAttribute("msg","该账号已经激活，您可以点击去登录了！");
            model.addAttribute("target","/login");
        }else{
            model.addAttribute("msg","激活失败，您提供的用户激活码错误！");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

    @GetMapping("/login")
    public String getLoginPage(){
        return "/site/login";
    }

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response){
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        response.setContentType("image/png");
        String s = CommunityUtil.generateUUID();
        Cookie cookie=new Cookie("owner",s);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        String kaptchaKey = RedisKeyUtils.getKaptchaKey(s);
        redisTemplate.opsForValue().set(kaptchaKey,text,60, TimeUnit.SECONDS);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("验证码输出错误！"+e);
        }
    }

    @PostMapping("/login")
    @LoginRequired
    public String login(@CookieValue("owner")String  kaptchaOwner ,Model model,HttpServletRequest request,HttpServletResponse response,String username,String password,String code,boolean rememberme){
        String kaptcha=null;
        if(StringUtils.isNotBlank(kaptchaOwner)){
            String kaptchaKey = RedisKeyUtils.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }
        if(kaptcha==null || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码有误！");
            return "/site/login";
        }
        int expiredSeconds=rememberme?CommunityConstant.REMEBER_EXPIRED_SECONDS:CommunityConstant.DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> result = userService.login(username, password, expiredSeconds);
        if(result.containsKey("ticket")){
            Cookie cookie=new Cookie("ticket",result.get("ticket").toString());
            cookie.setPath(request.getContextPath());
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        }else{
            model.addAttribute("usernameMsg",result.get("usernameMsg"));
            model.addAttribute("passwordMsg",result.get("passwordMsg"));
            return "/site/login";
        }
    }


    @GetMapping("/loginOut")
    public String loginOut(@CookieValue("ticket") String ticket,HttpServletRequest request){
        userService.loginOut(ticket);
        return "redirect:/login";
    }

    @GetMapping("/check/{username}")
    @ResponseBody
    public R checkUserName(@PathVariable("username")String username){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User one = userService.getOne(queryWrapper);
        if(one!=null){
            return R.error(-1,"存在该用户名，请重新选择！");
        }else{
            return R.ok().put("msg","该用户名不存在！");
        }
    }

    @GetMapping("/checkEmail/{email}")
    @ResponseBody
    public R checkEmail(@PathVariable("email")String email){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",email);
        User one = userService.getOne(queryWrapper);
        if(one!=null){
            return R.error(-1,"该邮箱已经被绑定，请重新选择！");
        }else{
            return R.ok().put("msg","该邮箱未被绑定！");
        }
    }




}
